home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1996 January / macformat-033.iso / mac / Shareware City / Developers / VideoToolbox / Demos / NoiseVBL.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-08-13  |  9.3 KB  |  252 lines  |  [TEXT/CWIE]

  1. /*
  2. NoiseVBL.c
  3.  
  4. There are two ways to synchronize your program to a video display. Apple
  5. recommends using the vertical blanking level interrupt (VBL). That approach is
  6. illustrated here. The other approach, which I normally prefer, is to use a side
  7. effect of loading the video cards clut: most video drivers don't return until
  8. the vertical blanking interval. The interrupt approach is more or less
  9. guaranteed to work on all video cards, since Apple more or less requires that it
  10. be supported by all video drivers. Its only disadvantage is that 
  11. interrupts must be enabled. I have the impression--though I haven't collected
  12. hard data--that interrupts steal a lot of time, depending on how busy AppleTalk,
  13. the disk, SCSI, keyboard, mouse, and even miscellaneous INITs that are driven by
  14. VBL interrupts. So when I really want to crank, to display movies, I prefer to
  15. use SetPriority(7) to temporarily suspend all interrupts. In that case the
  16. video-driver side effect approach is your only choice. However, be warned that
  17. some video drivers don't wait, and others take more than a frame to load the
  18. clut, so do some careful timing before you rely on it, i.e. run TimeVideo.
  19.  
  20. This program shows a noise movie, a dynamic random checkerboard, at 66.7 Hz! 
  21. Each frame is displayed by calling CopyWindows.c. After showing each frame once
  22. NoiseVBL cycles through them again. Thus to get a true impression of white noise you
  23. need to compute lots of noise frames, e.g. 100. This may require several
  24. megabytes, depending what your screen's pixel depth is set to.
  25.  
  26. HISTORY:
  27. 11/23/88 Denis Pelli wrote it.
  28.  
  29. 4/20/91 I updated this. It now has essentially no hardware dependencies. It does
  30. require that the video be in a slot, since it uses slot interrupts. A basic
  31. problem with the scheme is that interrupts seem to be shut out while the
  32. interrupt service routines are running. As a result the timing information is
  33. inaccurate since many 1 ms interrupts are lost during the call to
  34. CopyBitsQuickly(). I think the only solution to this would be to put the time
  35. consuming call to CopyBitsQuickly back in the main program, waiting for the
  36. interrupt service routine to give it permission to start each new frame.
  37.  
  38. 4/15/92 Removed all bugs and updated to work with THINK C 5. Now properly set A5
  39. in the interrupt service routines, using the method suggested in Tech Note 180.
  40. I removed the old attempt to disable AppleTalk, which now seems to hang up when
  41. it attempts to reenable AppleTalk. I also removed the clut manipulations.
  42.  
  43. 4/16/92    Put the noise in its own window. Run essentially continuously until
  44. user quits.
  45.  
  46. 8/19/92 Replaced obsolete TimeIt.c by new Timer.c. Timing seems to be fine now.
  47.  
  48. 8/22/92 dgp Moved most of the interrupt service routine code to 
  49. VBLInterruptServiceRoutine.c. Just for fun, I made the program use an alternate monitor,
  50. if available. Fixed a small bug that prevented display of noise on an alternate
  51. monitor if it had a different pixelSize than the main screen.
  52.  
  53. 9/15/92 dgp Updated to use new Timer.c.
  54.  
  55. 2/18/93    dgp    Added fpu test.
  56. 2/20/93    dgp    Call Require(), increased stack space.
  57. 7/7/93    dgp replaced call to CopyBitsQuickly by CopyBits, for compatibility with
  58. Radius PowerView.
  59. 3/19/94    dgp updated the call to Shuffle(), adding new required argument.
  60. 5/30/94    dgp    call StackGrow() before calling NoiseVBL().
  61. 7/27/94 dgp changed "thePort" to &qd.thePort, for broader compatibility, as suggested by
  62. Marty Wachter.
  63. 9/5/94 dgp removed assumption in printf's that int==short.
  64. 11/6/94 dgp updated to demonstrate use of GWorld and CopyWindows().
  65. 6/14/95 dgp updated to use Microseconds() instead of Timer.c. GetNextEvent() had the wrong
  66.     eventMask: "keyDown" instead of "keyDownMask". 
  67. */
  68. #include "VideoToolbox.h"
  69. #if UNIVERSAL_HEADERS
  70.     #include <LowMem.h>
  71. #else
  72.     #define LMGetMBarHeight() (* (short *) 0x0BAA)
  73.     #define LMSetMBarHeight(MBarHeightValue) ((* (short *) 0x0BAA) = (MBarHeightValue))
  74.     typedef unsigned long UInt32;
  75.     struct UnsignedWide {
  76.         UInt32 hi;
  77.         UInt32 lo;
  78.     };
  79.     typedef struct UnsignedWide UnsignedWide, *UnsignedWidePtr;
  80.     extern pascal void Microseconds(UnsignedWide *microTickCount)={0xA193, 0x225F, 0x22C8, 0x2280};
  81. #endif
  82.  
  83. /* The user may wish to adjust these. WIDTH should be a multiple of 4. */
  84. #define MAXFRAMES    200        // number of frames in movie
  85. #define WIDTH    256            /* width of displayed noise movie, in pixels */
  86. #define HEIGHT    256            /* height of displayed noise movie, in pixels */
  87. #define RANDOMPHASE 1        /* randomly shift each movie frame */
  88.  
  89. /* This is just for reference. The original is in VideoToolbox.h
  90. struct VBLTaskAndA5 {
  91.     volatile VBLTask vbl;
  92.     long ourA5;
  93.     void (*subroutine)(struct VBLTaskAndA5 *vblData);
  94.     GDHandle device;
  95.     long slot;
  96.     volatile long newFrame;                // Boolean
  97.     volatile long framesLeft;            // count down to zero
  98.     long framesDesired;
  99.     void *ptr;                            // use this for whatever you want
  100. };
  101. typedef struct VBLTaskAndA5 VBLTaskAndA5;
  102. */
  103.  
  104. void main(void);
  105. void NoiseVBL(void);
  106.  
  107. void main()
  108. {
  109.     long version;
  110.  
  111.     StackGrow(20000);
  112.     Require(gestalt8BitQD);
  113.     Gestalt(gestaltSystemVersion,&version);
  114.     if(version<0x700)PrintfExit("Sorry, I require at least System 7.\n"); // for Microseconds()
  115.     NoiseVBL();
  116. }
  117.  
  118. void NoiseVBL()
  119. {
  120.     int i,error,dx=32,dy=32,dt=1;
  121.     long frames;
  122.     unsigned long seed;
  123.     double s;
  124.     static char string[64];
  125.     Rect r;
  126.     short noiseI=0,noiseN=MAXFRAMES;
  127.     GWorldPtr noiseImage[MAXFRAMES];
  128.     short noiseSequence[MAXFRAMES]; /* shuffled sequence */
  129.     VBLTaskAndA5 noiseVBL;
  130.     WindowPtr window,oldPort;
  131.     EventRecord event;
  132.     int screen;
  133.     UnsignedWide microTicksStart,microTicks;
  134.     Boolean firstTime=1;
  135.     
  136.     assert(StackSpace()>5000);
  137.     GetDateTime(&seed);
  138.     srand(seed);
  139.     /* INITIALIZE QuickDraw */
  140.     #if (THINK_C || THINK_CPLUS || SYMANTEC_C)
  141.         console_options.nrows = 3;
  142.         printf("\n");
  143.     #elif __MWERKS__
  144.         SIOUXSettings.toppixel=LMGetMBarHeight()+19;    // allow for menu bar and title bar
  145.         SIOUXSettings.leftpixel=1;
  146.         SIOUXSettings.rows=3;
  147.         SIOUXSettings.autocloseonquit=0;
  148.         SIOUXSettings.showstatusline=0;
  149.         SIOUXSettings.asktosaveonclose=0;
  150.         printf("\n");
  151.     #else
  152.         InitGraf(&qd.thePort);
  153.         InitFonts();
  154.         InitWindows();
  155.         InitCursor();
  156.     #endif
  157.  
  158.     do{
  159.         if(GetScreenDevice(1)!=NULL)screen=ChooseScreen(1,"Which screen?");
  160.         else screen=0;
  161.         noiseVBL.device=GetScreenDevice(screen);
  162.     }while(noiseVBL.device==NULL);
  163.  
  164.     printf("Enter width of check in pixels (%d)?",dx);
  165.     gets(string);
  166.     sscanf(string,"%d",&dx);
  167.     printf("Enter height of check in pixels (%d)?",dy);
  168.     gets(string);
  169.     sscanf(string,"%d",&dy);
  170.     printf("Enter duration of check in frames (%d)?",dt);
  171.     gets(string);
  172.     sscanf(string,"%d",&dt);
  173.  
  174.     GetPort(&oldPort);
  175.     SetRect(&r,0,0,WIDTH,WIDTH);
  176.     CenterRectInRect(&r,&(*noiseVBL.device)->gdRect);
  177.     OffsetRect(&r,-(r.left%32),0);
  178.     window=NewCWindow(NULL,&r,"\pComputing noise ...",1,noGrowDocProc,(WindowPtr) -1L,0,0L);
  179.     SetPort(window);
  180.     for(i=0;i<MAXFRAMES;i++){
  181.         /* supply rect in global coordinates. The GWorld's pixels will be aligned with screen */
  182.         error=NewGWorld(&noiseImage[i],0,&r,NULL,NULL,keepLocal+useTempMem);
  183.         if(error)error=NewGWorld(&noiseImage[i],0,&r,NULL,NULL,keepLocal);
  184.         if(error)break;
  185.         error=NoiseFill(noiseImage[i],&noiseImage[i]->portRect,dx,dy,RANDOMPHASE);
  186.         LockPixels(noiseImage[i]->portPixMap);
  187.         if(error)break;
  188.     }
  189.     noiseN=i;
  190.     SetPort(oldPort);
  191.     printf("Using %d different frames of noise.\n",(int)noiseN);
  192.     for(i=0;i<noiseN;i++)noiseSequence[i]=i; /* initialize sequence */
  193.     FlushEvents(-1L,0);
  194.     printf("Hit any key to quit.\n");
  195.     FlushEvents(everyEvent,0);
  196.     SetWTitle(window,"\pNoiseVBL");
  197.     do{
  198.         SelectWindow(window);
  199.         Shuffle(noiseSequence,noiseN,sizeof(*noiseSequence));    /* shuffle the images */
  200.         noiseI=0;
  201.         noiseVBL.subroutine=NULL;    // use default
  202.         error=VBLInstall(&noiseVBL,noiseVBL.device,MAXFRAMES);
  203.         if(error)PrintfExit("VBLInstall: error %d\n",error);
  204.         noiseVBL.vbl.vblCount=1;    // Enable interrupt service routine
  205.         while(!noiseVBL.newFrame) ;    // wait for first frame
  206.         noiseVBL.newFrame=0;
  207.         while(!noiseVBL.newFrame) ;    // wait for second frame
  208.         Microseconds(µTicksStart);
  209.         frames=noiseVBL.framesLeft;
  210.         while(noiseVBL.framesLeft>1){
  211.             if(noiseVBL.newFrame){
  212.                 noiseVBL.newFrame=0;
  213.                 CopyWindows(noiseImage[noiseSequence[noiseI]],(CWindowPtr)window
  214.                     ,&noiseImage[0]->portRect,&window->portRect,srcCopy,NULL);
  215.                 if(noiseVBL.framesLeft%dt==0){
  216.                     noiseI++;
  217.                     if(noiseI>=noiseN) {
  218.                         Shuffle(noiseSequence,noiseN,sizeof(*noiseSequence));
  219.                         noiseI=0;
  220.                     }
  221.                 }
  222.             }
  223.         }
  224.         while(!noiseVBL.newFrame) ;    // wait for last frame
  225.         frames-=noiseVBL.framesLeft;
  226.         Microseconds(µTicks);
  227.         s=(microTicks.lo-microTicksStart.lo)
  228.             +(double)0x10000*0x10000*(microTicks.hi-microTicksStart.hi);
  229.         s/=1e6;
  230.         VBLRemove(&noiseVBL);
  231.         /*
  232.         The use of \n on the first time is a work around for a bug in the CodeWarrior 6.1
  233.         SIOUX console. It fails to update the screen when you send a \r, and only does so
  234.         when it receives a \n. Calling fflush(stdout) would force the screen to update, but
  235.         --another bug--also flushes stdin, discarding the user's keystrokes, which makes it
  236.         hard for the user to quit this program. So we use \n on the first time, so the user
  237.         gets to see at least the first timing result.
  238.         */
  239.         if(firstTime)printf("%.1f frames/s.\n",frames/s);
  240.         else printf("%.1f frames/s. \r",frames/s);
  241.         firstTime=0;
  242.     }while(!GetNextEvent(keyDownMask,&event));
  243.     FlushEvents(everyEvent,0);
  244.     for (i=0;i<noiseN;i++) DisposeGWorld(noiseImage[i]);
  245.     DisposeWindow(window);
  246.     #if (THINK_C || THINK_CPLUS || SYMANTEC_C)
  247.         abort();
  248.     #elif __MWERKS__
  249.         SIOUXSettings.autocloseonquit=1;
  250.     #endif
  251. }
  252.